package com.andrewdashin.twit2jabber.services.impl;

import com.andrewdashin.twit2jabber.domain.User;
import com.andrewdashin.twit2jabber.services.TwitterService;
import org.springframework.beans.factory.annotation.Required;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;

import java.util.*;

/**
 * User: dashin
 * Date: 26.11.2009
 * Time: 11:30:38
 */
public class TwitterServiceImpl implements TwitterService {
    // TODO make localization with properties files
    private final static String SYSTEM_ERROR = "System error happened: ";
    private final static Map<Class, String> TWITTER_ERROR_MESSAGES = new HashMap<Class, String>() {{
        put(TwitterException.E403.class, "Access forbidden");
        put(TwitterException.E404.class, "Resource doesn't exist (may be twitter account is in suspended state)");
        put(TwitterException.E50X.class, "Twitter service has problems. Please try some later");
        put(TwitterException.RateLimit.class, "You've over-used Twitter :)");
        put(TwitterException.Timeout.class, "Server timeout");
    }};

    @Override
    public List<Twitter.Status> getNewTwits(User user) {
        Twitter twitter = new Twitter(user.getTwitterUserName(), user.getTwitterPassword());
        List<Twitter.Status> timeline = twitter.getFriendsTimeline();

        List<Twitter.Status> timelineToSend = new LinkedList<Twitter.Status>();

        for (int i = timeline.size() - 1; i >= 0; i--) {
            long id = timeline.get(i).getId();
            if (user.getLastTwit() < id) {
                user.setLastTwit(id);
                timelineToSend.add(timeline.get(i));
            }
        }

        Collections.reverse(timelineToSend);
                
        return timelineToSend;
    }

    @Override
    public void newStatus(User user, String status) {
        Twitter twitter = new Twitter(user.getTwitterUserName(), user.getTwitterPassword());
        for (String shortStatus: twitter.splitMessage(status)) {
            twitter.setStatus(shortStatus);
        }
    }

    @Override
    public String getFriendlyMessage(TwitterException e) {
        // TODO make sure it really works
        String message = TWITTER_ERROR_MESSAGES.get(e);
        return SYSTEM_ERROR + (message != null ? message : "Unknown error");
    }

}
